package mail

import (
	. "gitee.com/aldrice/monitor/configs"
	. "gitee.com/aldrice/monitor/internal/common"
	"github.com/matcornic/hermes/v2"
	"gopkg.in/gomail.v2"
)

var HermesCore = &hermes.Hermes{
	Theme: new(hermes.Default),
	Product: hermes.Product{
		// Appears in header & footer of e-mails
		Name:        "监控系统 告警处理中心",
		Link:        Config.FrontendAddress,
		TroubleText: "如果 快捷按钮 没有正常工作, 可以直接点击以下链接.",
	},
}

// the smtp service supported by qq
const (
	SmtpQQPort = 465
	SmtpQQHost = "smtp.qq.com"
)

func SendMessage(username, server, dst string, detail AlarmItem, eType EmailType) error {
	m := gomail.NewMessage()

	// sender
	m.SetHeader("From", Config.SmtpService.Username)
	// receiver
	m.SetHeader("To", dst)
	// title
	m.SetHeader("Subject", string(eType))

	content, err := HermesCore.GenerateHTML(*generateEmail(
		username,
		server,
		detail,
		eType,
	))
	if err != nil {
		return err
	}

	// content
	m.SetBody("text/html", content)

	// create connection to smtp service server
	d := gomail.NewDialer(SmtpQQHost, SmtpQQPort, Config.SmtpService.Username, Config.SmtpService.AuthToken)

	// send email
	if err := d.DialAndSend(m); err != nil {
		return err
	}
	return nil
}

func generateEmail(username, object string, detail AlarmItem, eType EmailType) *hermes.Email {
	var body *hermes.Body
	switch eType {
	case EmailTypeNotify:
		body = getNotifyEmailBody(username, object, detail)
	default:
		body = getNotifyEmailBody(username, object, detail)
	}
	return &hermes.Email{Body: *body}
}
